<template>
	<!-- 付款页面 - 待付款跳转 -->
	<view class="pay_container">
		<!-- 支付倒计时 -->
		<view class="pay_count_down">
			<view class="pay_count_down_info">
				<view class="">等待付款</view>
				<view class="count_down_tip_text">请在 {{ count_down }} 完成支付</view>
			</view>
			<view class="pay_count_down_pic">
				<image class="pay_count_down_pic_img" src="../../static/pay/count_down.png" mode="widthFix"></image>
			</view>
		</view>
		<!-- 收货地址组件 -->
		<view class="address_component">
			<Address :noticeChoseAddress="noticeChoseAddress"></Address>	
		</view>
		<!-- 商品卡片组件 -->
		<view class="goods_card">
			<GoodsCard></GoodsCard>
		</view>
		<!-- 订单参数 -->
		<view class="order_params">
			<view class="should_price order_param_item">
				<view class="should_price_text">
					订单金额
				</view>
				<view class="should_price_value">
					￥{{ orderInfo.should_price }}
				</view>
			</view>
			<view class="coupon order_param_item">
				<view class="coupon_text">
					支付优惠
				</view>
				<view class="coupon_value">
					- ￥{{ discount }}
				</view>
			</view>
			<view class="real_price order_param_item">
				<view class="real_price_text">
					实付金额
				</view>
				<view class="real_price_value">
					￥<span style="font-size: 15px;">{{ orderInfo.real_price }}</span>
				</view>
			</view>
		</view>
		<!-- 下单时间，订单编号 -->
		<view class="order_time_id">
			<view class="order_time order_param_item" >
				<view class="order_time_text">
					下单时间
				</view>
				<view class="order_time_value">
					{{ orderInfo.createTime }}
				</view>
			</view>
			<view class="order_id order_param_item">
				<view class="order_id_text">
					订单编号
				</view>
				<view class="order_id_value">
					{{ orderInfo.order_id }}
				</view>
			</view>
		</view>
		<!-- 结算框 -->
		<view class="settle_box">
			<view class="cancel_btn" @click="cancelOrderHandle">
				取消订单
			</view>
			<view class="settle_btn">
				<view class="should_pay">
					应付金额: <span style="color: red;">
								￥<span style="font-size: 15px;">{{ orderInfo.real_price }}</span>	
							</span>
				</view>
				<view class="settle_btn_box">
					<button class="settle_btn_B" type="default" @click="payHandle">立即支付</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { onLoad, onShow } from '@dcloudio/uni-app';
import { ref, onMounted } from 'vue';
import Address from '../../components/Address/Address.vue';
import GoodsCard from '../../components/GoodsCard/GoodsCard.vue';
import dayjs from "dayjs"

// 订单ID
let payOrderId = ref('');
// 订单信息
let orderInfo = ref({});
// 支付倒计时
let count_down = ref('00:00');
// 收货地址选择标识
let choseAddressFlag = ref();

// 计算折扣
let discount = ref("0.00");

let prePayParam  = ref();

onLoad((options) => {
	payOrderId.value = options.orderId;
});

onMounted(() => {
	getOrderInfo();
	uni.setStorageSync("aginPayStatus", false);
});


onShow(()=>{
	if(uni.getStorageSync("aginPayStatus")){
		setTimeout(()=>{
			checkOrderPayStatus();
		}, 5000)
	}
})

// 立即支付处理器
function payHandle(){
	submitPayment();
}

// 提交支付请求
// 唤起支付宝支付，获取支付页面
const submitPayment = async (orderData) => {
	
	// console.log(orderInfo.value);
	
  // 构建请求参数
  let paramObj = {
    traceNo: payOrderId.value, // 使用订单编号作为交易号
    subject: "【Uni商城购物】" , // 订单标题
    totalAmount: orderInfo.real_price // 订单金额
  }
  
  prePayParam.value = paramObj; // 存储预支付订单返回的参数
  
  // console.log("预支付订单参数===>>", prePayParam.value);
  
  uni.setStorageSync("prePayOrderId", paramObj.traceNo);
  
  try {
    // 显示加载状态
    uni.showLoading({
      title: '加载支付界面...'
    });
    
    // 发起请求获取支付表单
    const response = await uni.request({
      // url: "http://localhost:9088/alipay/pay_mobile", // 本地测试
      url: "https://php.meibug.cn/japi/alipay/pay_mobile", // 线上测试
      method: 'POST',
      data: paramObj,
      dataType: 'text', // 接收为文本格式
    });
    
    uni.hideLoading();
    
    if (response.statusCode === 200) {
		uni.setStorageSync("aginPayStatus", true);
      // 打开支付弹窗
      openPaymentPopup(response.data);
    } else {
      uni.showToast({
        title: '获取支付信息失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: `支付请求失败：${error.errMsg || '未知错误'}`,
      icon: 'none'
    });
    console.error("支付请求失败:", error);
  }
}

// 显示支付弹窗
function openPaymentPopup(htmlForm) {
	
	// 创建一个包含HTML表单的弹窗
	const popupDiv = document.createElement('div');
	popupDiv.id = 'payment-popup';
	popupDiv.style.position = 'fixed';
	popupDiv.style.top = '0';
	popupDiv.style.left = '0';
	popupDiv.style.width = '100%';
	popupDiv.style.height = '100%';
	popupDiv.style.backgroundColor = 'rgba(0,0,0,0.5)';
	popupDiv.style.zIndex = '9999';
	popupDiv.style.display = 'flex';
	popupDiv.style.flexDirection = 'column';
	popupDiv.style.justifyContent = 'center';
	popupDiv.style.alignItems = 'center';
	
	// 创建内容容器
	const contentDiv = document.createElement('div');
	contentDiv.innerHTML = "调起支付中..."
	contentDiv.style.backgroundColor = '#fff';
	contentDiv.style.borderRadius = '8px';
	contentDiv.style.padding = '20px';
	contentDiv.style.width = '90%';
	contentDiv.style.maxWidth = '400px';
	contentDiv.style.maxHeight = '80%';
	contentDiv.style.overflow = 'auto';
	
	// 添加标题
	const titleDiv = document.createElement('div');
	titleDiv.style.fontSize = '18px';
	titleDiv.style.fontWeight = 'bold';
	titleDiv.style.marginBottom = '15px';
	titleDiv.style.textAlign = 'center';
	titleDiv.innerText = '请扫码支付';
	
	// 添加关闭按钮
	const closeBtn = document.createElement('button');
	closeBtn.innerText = '关闭';
	closeBtn.style.position = 'absolute';
	closeBtn.style.top = '10px';
	closeBtn.style.right = '10px';
	closeBtn.style.padding = '5px 10px';
	closeBtn.style.border = 'none';
	closeBtn.style.borderRadius = '4px';
	closeBtn.style.backgroundColor = '#f5f5f5';
	closeBtn.onclick = closePaymentPopup;
	
	// 设置HTML表单内容
	contentDiv.innerHTML += htmlForm;
	
	// 查找并处理表单，设置为自动提交
	setTimeout(() => {
	const form = contentDiv.querySelector('form');
	if (form) {
		// 隐藏表单的提交按钮
		const submitBtn = form.querySelector('input[type="submit"]');
		if (submitBtn) {
		submitBtn.style.display = 'none';
		}
		
		// 自动提交表单
		form.submit();
	}
	}, 100);
	
	// 组装弹窗
	contentDiv.appendChild(closeBtn);
	popupDiv.appendChild(contentDiv);
	document.body.appendChild(popupDiv);
	
}

// 关闭支付弹窗
function closePaymentPopup() {
  const popup = document.getElementById('payment-popup');
  if (popup) {
	  checkOrderPayStatus();
	  document.body.removeChild(popup);
  }
}

function checkOrderPayStatus(){
	uni.showLoading({
		title: "正在检查支付结果..."
	})
	
	// 将setTimeout改为Promise并使用async回调
	return new Promise((resolve) => {
		setTimeout(async () => {
			let res = await uni.$http.get(`/order/status/${uni.getStorageSync("prePayOrderId")}`);
			// console.log("==检查结果==》", res);
			if(res.data.code == 0){
				uni.hideLoading();
				uni.$showT("订单状态异常");
				resolve(0);
				return 0;
			}
			
			if(res.data.data == 1){
				uni.hideLoading();
				// 代表用户支付成功
				successPayAfterHandle();
				resolve(1);
			}else{
				uni.hideLoading();
				// 代表用户支付成功
				uni.$showT("未检测到支付，请及时支付哦.");
				// setTimeout(() => {
				// 	uni.switchTab({
				// 		url: "/pages/my/my"
				// 	});
				// }, 1500);
				resolve(-1);
			}	
		}, 1500);
	});
}


// 支付成功处理器
function successPayAfterHandle(){
	uni.showToast({
		title: '支付成功',
		icon: "none"
	});
	
	// 跳转到订单页面"待收货"状态栏
	setTimeout(()=>{
		uni.redirectTo({
			url: `/subPkg2/order/order?state=1` // 跳转后选择状态为"待付款"
		})
	}, 1000)
}

// 取消订单按钮
function cancelOrderHandle(){
	// 确定取消按钮
	uni.showModal({
		title: '提示',
		content: '确定删除该订单？',
		success: function (res) {
			if (res.confirm) {
				execCancelOrderHanlde()
			} else if (res.cancel) {
				// console.log("不取消");
			}
		}
	});
}

async function execCancelOrderHanlde(){
	const res = await uni.$http.put(`/orderInfos/cancelOrder/${payOrderId.value}`);
	if(res.data.code == 1){
		uni.showToast({
			title: '订单删除成功',
			icon: "none"
		});
		
		setTimeout(()=>{
			uni.navigateTo({
				url: `/subPkg2/order/order?state=5` // 跳转后选择状态为"已取消"
			})
		}, 1000)
		return 1;
	}
	
	uni.showToast({
		title: '订单删除失败',
		icon: "none"
	});
}

// 获取待支付的订单信息
async function getOrderInfo() {
	const res = await uni.$http.get(`/order/getById/${payOrderId.value}`);
	
	if(res.data.data.use_coupon == 0){
		discount.value = "0.00";
	}else{
		discount.value = res.data.data.coupon.value.toFixed(2)
		// console.log("使用了优惠券");
	}
	
	orderInfo.value = res.data.data;
	
	// 格式化时间
	orderInfo.value["createTime"] = dayjs(orderInfo.value.create_time).format("YYYY-MM-DD HH:mm:ss");
	
	// console.log('待支付订单ID：', orderInfo.value);
	// 处理器倒计时
	countDownHandle(res.data.data.create_time);
}

function countDownHandle(orderTime) {
	const orderDate = new Date(orderTime);
	const endDate = new Date(orderDate.getTime() + 15 * 60 * 1000); // 下单后15分钟的时间

	const updateTime = () => {
		const now = new Date();
		const difference = Math.floor((endDate - now) / 1000); // 计算剩余时间差（秒）

		if (difference > 0) {
			const minutes = Math.floor(difference / 60);
			const seconds = difference % 60;
			count_down.value = `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
		} else {
			count_down.value = '00:00'; // 倒计时结束
			clearInterval(interval); // 清除定时器
		}
	};

	updateTime(); // 初始化显示

	const interval = setInterval(updateTime, 1000); // 每秒更新

	return count_down.value;
}

// 收货地址组件通知修改是否选择了收货地址
function noticeChoseAddress(isSelect){
	if(isSelect){
		choseAddressFlag.value = isSelect;
	}
}
</script>

<style lang="scss" scoped>
.pay_count_down {
	display: flex;
	justify-content: space-between;
	padding: 0px 15rpx;
	align-items: center;
	background: linear-gradient(to right, #ef6134, #da6d4a);
	color: white;
}

.pay_count_down_btn_B {
	background-color: #ffa041;
	color: white;
	height: 70rpx;
	font-size: 15px;
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 0px 30rpx;
}

.pay_count_down_pic {
	width: 30%;
}

.pay_count_down_pic_img {
	width: 100%;
}

.count_down_tip_text {
	font-size: 14px;
	padding-top: 10rpx;
}

.goods_card{
	width: 96%;
	margin: 0 auto;
	margin-top: 15rpx;
}

.order_param_item{
	display: flex;
	justify-content: space-between;
	padding: 30rpx 30rpx;
	color: #4d4d4d;
}

.order_params{
	width: 96%;
	margin: 0 auto;
	margin-top: 20rpx;
	background-color: #fff;
	font-size: 13px;
}

.real_price_value{
	color: #ea6d1a;
}

.real_price_text{
	color: #ea6d1a;
	font-size: 15px;
}

.real_price{
	background-color: #f7f7f7;
}

.order_time_id{
	background-color: #fff;
	width: 96%;
	margin: 0 auto;
	margin-top: 20rpx;
	font-size: 13px;
}

.settle_box{
	background-color: #fff;
	position: fixed;
	bottom: 0px;
	height: 100rpx;
	width: 100vw;
	display: flex;
	justify-content: space-between;
	font-size: 13px;
	align-items: center;
	padding: 0px 15rpx;
	color: #4d4d4d;
}

.settle_btn{
	display: flex;
	align-items: center;
	padding-right: 35rpx;
}

.settle_btn_B{
	background-color: #ff7f17;
	color: white;
	font-size: 14px;
	border-radius: 15px;
}

.should_pay{
	padding-right: 30rpx;
}
</style>
